//
//  NSArray+Ex.m
//  Ashton
//
//  Created by pengpeng on 2023/11/16.
//  Copyright © 2023 Falcon Automation. All rights reserved.
//

#import "NSArray+Ex.h"

@implementation NSArray (Ex)

- (id)objectNullableAtIndex:(NSUInteger)index {
    if (self.count > index) {
        return [self objectAtIndex:index];
    } else {
        return nil;
    }
}

- (NSArray *)map:(id  _Nonnull (^)(id _Nonnull))block {
    if (!block) { return @[]; }
    
    NSMutableArray *array = [NSMutableArray array];
    for (id object in self) {
        [array addObject:block(object)];
    }
    return array;
}

- (NSArray *)mapWithIndex:(id  _Nonnull (^)(id _Nonnull, NSInteger))block {
    if (!block) { return @[]; }
    
    NSMutableArray *array = [NSMutableArray array];
    NSInteger count = self.count;
    for (NSInteger index = 0; index < count; index ++) {
        id object = [self objectAtIndex:index];
        [array addObject:block(object, index)];
    }
    return array;
}

- (NSArray *)filter:(BOOL (^)(id _Nonnull))block {
    if (!block) { return @[]; }
    
    NSMutableArray *array = [NSMutableArray array];
    for (id object in self) {
        if (block(object)) {
            [array addObject:object];
        }
    }
    return array;
}

- (BOOL)contains:(BOOL (^)(id _Nonnull))block {
    if (!block) { return NO; }
    
    for (id object in self) {
        if (block(object)) {
            return YES;
        }
    }
    return NO;
}

- (id)first:(BOOL (^)(id _Nonnull))block {
    if (!block) { return nil; }
    
    for (id object in self) {
        if (block(object)) {
            return object;
        }
    }
    return nil;
}

- (NSInteger)firstIndex:(BOOL (^)(id _Nonnull))block {
    if (!block) { return -1; }
    
    NSInteger count = self.count;
    for (NSInteger index = 0; index < count; index ++) {
        id object = [self objectAtIndex:index];
        if (block(object)) {
            return index;
        }
    }
    return -1;
}

/// 一键枚举, for循环, index
- (void)enumeration:(void (^)(id _Nonnull, NSInteger, NSInteger))block {
    if (!block) { return; }
    
    NSInteger count = self.count;
    for (NSInteger index = 0; index < count; index ++) {
        id object = [self objectAtIndex:index];
        block(object, index, count);
    }
}

@end

@implementation NSMutableArray (Ex)

- (void)remove:(BOOL (^)(id _Nonnull))block {
    if (!block) { return; }
    
    NSInteger count = self.count;
    
    NSMutableIndexSet *indexSet = [NSMutableIndexSet indexSet];
    for (NSInteger index = 0; index < count; index ++) {
        id object = [self objectAtIndex:index];
        if (block(object)) {
            [indexSet addIndex:index];
        }
    }
    [self removeObjectsAtIndexes:indexSet];
}

@end
